import {
	createRouter,
	createWebHashHistory,
	type RouteLocationNormalized,
	type NavigationGuardNext,
	type RouteRecordRaw
} from 'vue-router'
import routes from '@/router/routes'

const router = createRouter({
	history: createWebHashHistory(),
	routes: routes as unknown as RouteRecordRaw[]
})

// 全局路由前置守卫
router.beforeEach(
	(to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
		const jwtToken = useTokenStore(Pinia) // 这样做是可行的，因为路由器是在其被安装之后开始导航的
		if (jwtToken.getToken) {
			if (to.meta.authType === '?') {
				next('/')
			} else {
				if (from.path === '/') {
					// 页面刷新处理
					Api.post('/rbac/adminer/auth-info', [], true).then((res: any) => {
						const adminer = useAdminerStore()
						adminer.updateAdminer(res.adminerInfo)
						adminer.updatePermissions(res.permissionPaths)
					})
				}
			}
		} else {
			if (!to.meta.authType || to.meta.authType === '@') {
				if (to.path !== '/login') next('login')
			}
		}
		next()
	}
)

// 全局路由后置守卫
// router.afterEach((to, from) => {})

export default router
